import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// import store from '@/store'

// 导入需要使用路由进行切换的组件
import home from '@/views/home/home'
import category from '@/views/category/category'
import shopcart from '@/views/shopcart/shopcart'
import user from '@/views/user/user'
import productList from '@/views/product-list/product-list'
import productDetail from '@/views/product-detail/product-detail'
import login from '@/views/login/login'
import profile from '@/views/profile/profile'

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: home,
    meta: {
      index: 1
    }
  },
  {
    path: '/category',
    component: category,
    meta: {
      index: 1
    }
  },
  {
    path: '/shopcart',
    component: shopcart,
    meta: {
      index: 1,
      auth: true
    }
  },
  {
    path: '/user',
    component: user,
    meta: {
      index: 1,
      auth: true
    }
  },
  {
    path: '/product-list',
    component: productList,
    meta: {
      index: 2
    }
  },
  {
    path: '/product/:id',
    component: productDetail,
    meta: {
      index: 3
    }
  },
  {
    path: '/login',
    component: login,
    meta: {
      index: 2
    }
  },
  {
    path: '/profile',
    component: profile,
    meta: {
      index: 2,
      auth: true
    }
  }
]

const router = new VueRouter({
  routes
})


// 只要跳转路由都会触发 beforeEach
// 路由导航钩子函数
// 路由拦截
router.beforeEach((to, from, next) => {
  // console.log(to) // 去哪儿
  // console.log(from) // 从哪儿来
  // if (to.path == '/login' || to.path == '/home' || to.path == '/category') {
  //   next()
  // } else {
  //   if (store.state.userinfo.username) {
  //     next()
  //   } else {
  //     next('/login')
  //   }
  // }

  // 判断路由是否需要登录验证
  if (to.meta.auth) {
    // 判断是否保存的有用户名，如果有表示已经登录，如果没有这跳转到登录界面
    if (localStorage.getItem('userinfo')) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router

// 第一种解决方案: 在main.js中发起获取用户信息的请求,可能出现的问题是请求耗时过长导致数据回来之前已经执行了router中的路由拦截

// 第二种解决方案: 路由拦截中不要去判断内存中的store数据，判断本地存储中是否有已经登录的信息
